import WeChat from 'wechat-jssdk/dist/client'
import Vue from 'vue'
const state = {
  wechat: null,
  location: {}
}
const getters = {
  wechat: state => state.wechat
}
const actions = {
  /**
   * @purpose 获取jssdk签名
   * @param commit
   * @param state
   * @returns {Promise<any>}
   */
  sdk ({commit, state}) {
    return new Promise((resolve, reject) => {
      let $vue = new Vue()
      let auto = setTimeout(() => {
        $vue.showLoading()
      }, 2000)
      $vue
        .$api
        .wechat
        .jssdk()
        .then(sign => {
          clearTimeout(auto)
          $vue.closeLoading()
          sign.success = function () {
            resolve(state.wechat.wx)
          }
          sign.error = function (res) {
            reject(res)
          }
          let wechat = new WeChat(sign)
          commit('setWeChat', wechat)
        })
        .catch(e => {
          reject(e)
        })
    })
  }
}
const mutations = {
  setWeChat: (state, wechat) => {
    state.wechat = wechat
  }
}
export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
